/*
Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
*/

class Solution {
public:
    typedef pair<int, int> Point;
    bool existHelper(vector<vector<char> > &board,
        int curx, int cury, const string &word, int wpos)
    {
        int m = board.size();
        int n = board[0].size();
        if ((curx < 0 || curx >=m) ||
            (cury < 0 || cury >=n) ||
            (board[curx][cury] != word[wpos]))
        {
            return false;
        }
        // find one match if last char matches
        if (++wpos == word.length()) {
            return true;
        }
        char cnow = board[curx][cury];
        board[curx][cury] = '\0';
        // try different directions
        Point curleft(curx, cury-1);
        Point curright(curx, cury+1);
        Point curup(curx-1, cury);
        Point curdown(curx+1, cury);
        if (existHelper(board, curx, cury-1, word, wpos) ||
            existHelper(board, curx, cury+1, word, wpos) ||
            existHelper(board, curx-1, cury, word, wpos) ||
            existHelper(board, curx+1, cury, word, wpos))
        {
            return true;
        }
        board[curx][cury] = cnow;
        return false;
    }
    bool exist(vector<vector<char> > &board, string word) {
        int m = board.size();
        int n = board[0].size();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == word[0]) {
                    vector<vector<char> >newboard = board;
                    if (existHelper(board, i, j, word, 0))
                        return true;
                }
            }
        }
        return false;
    }
};
